from __future__ import absolute_import

import os
import logging
import yaml

from twisted.internet import reactor

from autobahn.wamp import WampClientFactory, WampClientProtocol
 
import yadtshell.settings


class WampBroadcaster(object):
    def __init__(self, host, port, target):
        self.host = host
        self.port = port
        self.target = target
        self.url = 'ws://%s:%s/' % (self.host, self.port)
        self.factory = None
        self.client = None
        self.logger = logging.getLogger('broadcaster')

    def connect(self):
        if self.client:
            return
        broadcaster = self
        self.logger.debug('trying to connect to %s' % self.url)
        class BroadcastClientProtocol(WampClientProtocol):
            def onSessionOpen(self):
                broadcaster.client = self
                broadcaster.logger.info('connected to broadcast-server %s' % broadcaster.url)

        self.factory = WampClientFactory(self.url)
        self.factory.protocol = BroadcastClientProtocol
        reactor.connectTCP(self.host, self.port, self.factory)

    def sendFullUpdate(self, data):
        return self._sendEvent('full-update', data)

    def sendServiceChange(self, data):
        return self._sendEvent('service-change', data)

    def _sendEvent(self, id, data):
        if not self.client:
            key = 'not_connected_warning_sent'
            if not getattr(self, key, False):
                setattr(self, key, True)
                self.logger.warning('could not connect to broadcaster %s' % self.url)

            self.logger.debug('not connected, dropping data: %s' % data)
            return
        self.client.publish(self.target, {
            'id': id,
            'target': self.target,
            'payload' : data
        })


